import { defineStore } from 'pinia'

const useOrderStore = defineStore('order', {
    state() {
        return {
            receiveMan: undefined,
            /** 搜索列表 保存本地数据*/
            searchHistory: getHistory(),
            /** 智能客服搜索列表*/
            list: getSearchHistory(),
            /**
             * 订单管理页面 缓存
             * 以订单号存储相关 处理数据 避免重复计算
             */
            orders: {} as any
        }
    },
    actions: {
        addDealedData2Cache({ id, list }: { id: string; list: Array<any> }) {
            this.orders[id] = list
        },
        addServerList(data: any) {
            let index = this.list.indexOf(data)
            if (index >= 0) this.list.splice(index, 1)
            this.list.push(data)
            saveServerHistory(this.list)
        },
        clearServerHistory(){
            this.list = []
            uni.removeStorageSync('merchant_server_list')
        },
        clearHistory() {
            this.searchHistory = []
            uni.removeStorageSync('merchant_search_history')
        },
        addHistory(data: string) {
            let index = this.searchHistory.indexOf(data)
            if ( index > -1) {
                this.searchHistory.splice(index,1)
            }
            this.searchHistory.push(data)
            uni.setStorageSync('merchant_search_history', this.searchHistory)
        },
    }
})

function getHistory() {
    return uni.getStorageSync('merchant_search_history') || []
}

function getSearchHistory() {
    return uni.getStorageSync('merchant_server_list') || []
}

function saveServerHistory(arr: Array<any>) {
    uni.setStorageSync('merchant_server_list', arr)
}


export default useOrderStore
